package com.xyhuo.leetcode.december;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 有效的括号
 * https://leetcode.cn/problems/valid-parentheses/
 *
 * @time 2023/12/5
 */
public class IsValid {

    public boolean isValid(String s) {
        char[] charArray = s.toCharArray();
        Deque<Character> deque = new ArrayDeque<>();
        for (char item : charArray) {
            if (item == '[' || item == '(' || item == '{') {
                deque.add(item);
            } else {
                if (deque.isEmpty()) {
                    return false;
                }
                Character last = deque.getLast();
                if (item == ']') {
                    if (last == '[') {
                        deque.removeLast();
                    } else {
                        return false;
                    }
                } else if (item == ')') {
                    if (last == '(') {
                        deque.removeLast();
                    } else {
                        return false;
                    }
                } else if (item == '}') {
                    if (last == '{') {
                        deque.removeLast();
                    } else {
                        return false;
                    }
                }
            }
        }
        if (deque.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}
